package com.sevennotes.classtable.ui.pages.recordpage

import android.util.Log
import android.widget.DatePicker
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round
import androidx.compose.ui.zIndex
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.sevennotes.classtable.config.Config
import com.sevennotes.classtable.model.ClassRecordMonthStatis
import com.sevennotes.classtable.model.ClassRecordWithName
import com.sevennotes.classtable.ui.pages.components.BarChartCard
import com.sevennotes.classtable.ui.pages.components.ItemCell
import com.sevennotes.classtable.ui.pages.components.RecordCell
import com.sevennotes.classtable.ui.pages.components.myDatePicker
import com.sevennotes.classtable.ui.pages.components.pickerPreview
import com.sevennotes.classtable.ui.pages.main_screen.MainViewModel
import com.sevennotes.classtable.ui.pages.main_screen.RecordPageState
import com.sevennotes.classtable.utils.FakeDataUtil
import com.sevennotes.classtable.utils.TimeUtil
import java.util.*

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun RecordPage(
  rState: RecordPageState,
  classRecords: LazyPagingItems<ClassRecordWithName>,
  onSearchValueChange: (String) -> Unit,
  onFromChange: (Date) -> Unit,
  onToChange: (Date) -> Unit,
  onDelete: (ClassRecordWithName) -> Unit,
  onYearPick: (List<String>) -> Unit,
  onMonthPick: (List<String>) -> Unit,
) {
  val context = LocalContext.current
  var showFilter by remember { mutableStateOf(false) }
  val yearPickerRowState = rememberPickerRowState(
    allItemList = rState.allRecordedYears,
    onSelectItemChanged = onYearPick
  )
  val monthPickerRowState = rememberPickerRowState(
    allItemList = List(12) { (it + 1).toString() },
    onSelectItemChanged = onMonthPick
  )
  Column(
    modifier = Modifier.fillMaxSize()
  ) {
    /**
     * 搜索和过滤器
     */
    AnimatedVisibility(visible = showFilter) {
      Column {
        OutlinedTextField(
          modifier = Modifier
            .fillMaxWidth()
            .padding(10.dp),
          value = rState.searchStr,
          onValueChange = onSearchValueChange,
          label = { Text("搜索") },
          trailingIcon = {
            Row {
              IconButton(onClick = { onSearchValueChange("") }) {
                Icon(imageVector = Icons.Filled.Delete, contentDescription = "delete")
              }
            }
          },
          singleLine = true
        )
        PickerRow(
          pickerRowState = yearPickerRowState,
          shape = RoundedCornerShape(8.dp)
        )
        PickerRow(
          pickerRowState = monthPickerRowState
        )
      }
    }

    Box(
      modifier = Modifier.fillMaxWidth().clickable { showFilter = !showFilter },
      contentAlignment = Alignment.Center
    ) {
      Icon(imageVector = if (showFilter) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
        modifier = Modifier.padding(vertical = 4.dp),
        contentDescription = "open")
    }

    Spacer(modifier = Modifier.height(6.dp))

    ItemCell {
      Text(text = "共有记录数: ")
      Text(text = "${classRecords.itemCount}")
      Text(text = " 条")
    }
    LazyColumn(modifier = Modifier.fillMaxWidth()) {
      val itemCount = classRecords.itemCount
      var dateStr: String? = null
      for (index in 0 until itemCount) {
        val cr = classRecords.peek(index)
        val currentdate =
          cr?.classRecord?.startTime?.let { TimeUtil.formatDate(it, "yyyy年MM月") }
        if (cr != null && currentdate != dateStr) {
          stickyHeader {
            Box(
              modifier = Modifier
                .fillMaxWidth()
                .background(color = Config.dividerColor)
            ) {
              Text(
                text = currentdate ?: "日期错误",
                modifier = Modifier.offset(x = 10.dp)
              )
            }
          }
        }
        item {
          val item = classRecords[index]
          if (item == null) {
            ItemCell(
              modifier = Modifier.fillMaxWidth(),
              hArrangement = Arrangement.Center
            ) {
              Text(text = "加载中..")
            }
          } else {
            RecordCell(
              editable = rState.editable.value,
              record = item,
              onDeleteClick = { onDelete(item) }
            )
          }
        }
        dateStr = currentdate
      }
    }
  }
}

@Composable
fun PickerRow(
  modifier: Modifier = Modifier,
  pickerRowState: PickerRowState,
  shape: Shape = CircleShape,
  selectedColor: Color = MaterialTheme.colors.primary,
  unselectedColor: Color = MaterialTheme.colors.onSurface.copy(alpha = 0.12f),
  textStyle: TextStyle = MaterialTheme.typography.subtitle1
) {
  val scrollState = rememberScrollState()
  Box {
    Row(
      modifier = Modifier
        .horizontalScroll(scrollState)
    ) {
      val boxModifier = if (shape == CircleShape) Modifier.size(60.dp) else Modifier
      Box(
        modifier = boxModifier
          .padding(8.dp)
          .background(
            color = if (pickerRowState.allSelected) selectedColor else unselectedColor,
            shape = shape
          )
          .clickable { pickerRowState.onAllSelectClick() },
        contentAlignment = Alignment.Center
      ) {
        Text(
          text = "all",
          style = textStyle,
          color = if (pickerRowState.allSelected) Color.White else unselectedColor,
          modifier = Modifier.padding(8.dp)
        )
      }
      pickerRowState.allItemList.forEach { item ->
        Box(
          modifier = boxModifier
            .padding(8.dp)
            .background(
              color = if (pickerRowState.selectedItemList.contains(item)) selectedColor else unselectedColor,
              shape = shape
            )
            .clickable { pickerRowState.onItemSelect(item) },
          contentAlignment = Alignment.Center
        ) {
          Text(
            text = item,
            style = textStyle,
            color = if (pickerRowState.selectedItemList.contains(item)) Color.White else unselectedColor,
            modifier = Modifier.padding(8.dp)
          )
        }
      }
    }
  }
}


@Composable
fun rememberPickerRowState(
  allItemList: List<String>,
  selectedItemList: List<String> = allItemList,
  onSelectItemChanged: (List<String>) -> Unit = {}
): PickerRowState {
  return remember { PickerRowState(allItemList, selectedItemList, onSelectItemChanged) }
}

class PickerRowState(
  val allItemList: List<String>,
  selectedItemList: List<String>,
  val onSelectItemChanged: (List<String>) -> Unit = {}
) {
  val selectedItemList: SnapshotStateList<String> = mutableStateListOf()
  var allSelected by mutableStateOf(false)

  init {
    this.selectedItemList.addAll(selectedItemList)
    if (this.selectedItemList.size >= allItemList.size) allSelected = true
    onSelectItemChanged(selectedItemList.toList())
  }

  private fun <T> SnapshotStateList<T>.toggle(element: T) {
    if (contains(element)) remove(element) else add(element)
  }

  private fun <T> SnapshotStateList<T>.toggleAll(list: List<T>) {
    clear()
    addAll(list)
  }

  fun onItemSelect(item: String) {
    selectedItemList.toggle(item)
    allSelected = selectedItemList.size >= allItemList.size
    onSelectItemChanged(selectedItemList.toList())
  }

  fun onAllSelectClick() {
    if (!allSelected) {
      selectedItemList.toggleAll(allItemList)
    } else {
      selectedItemList.clear()
    }
    allSelected = !allSelected
    onSelectItemChanged(selectedItemList.toList())
  }
}

@Preview(showBackground = true)
@Composable
fun PickerRowPreview() {
  val list1 = List(5) { (it + 2018).toString() }
  val list2 = List(12) { (it + 1).toString() }
  Column {
    PickerRow(
      modifier = Modifier.fillMaxWidth(),
      pickerRowState = rememberPickerRowState(allItemList = list1),
      shape = RoundedCornerShape(15.dp)
    )
    PickerRow(
      modifier = Modifier.fillMaxWidth(),
      pickerRowState = rememberPickerRowState(allItemList = list2)
    )
  }
}

@Preview(showBackground = true)
@Composable
fun RecordPagePreview() {
  val recordPageState by remember {
    mutableStateOf(RecordPageState(
      allRecordedYears = List(5) { (it + 2019).toString() }
    ))
  }
  LaunchedEffect(Unit) {
    recordPageState.editable.value = true
  }
  val fakeData = FakeDataUtil.testPagerFakeData.collectAsLazyPagingItems()
  RecordPage(
    rState = recordPageState,
    classRecords = fakeData,
    onSearchValueChange = {},
    onFromChange = {},
    onToChange = {},
    onDelete = {},
    onYearPick = {},
    onMonthPick = {}
  )
}
